package com.weixin.web;

import com.agent.entity.Dict;
import com.agent.entity.RepaireInfo;
import com.agent.entity.User;
import com.agent.service.IDictService;
import com.agent.service.IRepaireInfoService;
import com.agent.service.UserService;
import com.agent.shiro.ShiroUser;
import com.agent.spring.websocket.SpringWebSocketHandler;
import com.agent.util.CommonUtils;
import com.agent.util.Constants;
import com.agent.util.DateUtil;
import com.agent.util.MyPropertiesConfigurer;
import com.agent.vo.RepaireCustomerVO;
import com.agent.vo.RepaireInfoVO;
import com.weixin.pojo.Text;
import com.weixin.pojo.Textcard;
import com.weixin.pojo.WXMsg;
import com.weixin.pojo.WXUser;
import com.weixin.service.TokenUtil;
import com.weixin.service.WeixinNotifyService;
import com.weixin.util.WXUserUtil;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.ListUtils;
import org.apache.poi.util.ArrayUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/weixin/")
@Slf4j
public class WXRepaireController {

    @Resource(name = "repaireInfoService")
    IRepaireInfoService service;
    @Autowired
    UserService userService;
    @Resource(name = "dictService")
    IDictService dictService;

    @Resource(name = "weixinNotifyService")
    WeixinNotifyService weixinNotifyService;

    @Autowired
    TokenUtil tokenUtil;

    @Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }

    @RequestMapping(value = "repairInfo" ,method = RequestMethod.POST ,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String addWorkOrder(@RequestParam("file") MultipartFile file, RepaireInfoVO repaireInfoVO, Model model, HttpServletRequest request){
        if(!tokenUtil.checkToken(Constants.WX_REPAIRE_TOKEN,repaireInfoVO.getToken())){
            log.info("the token is invalid token is {} ");
            model.addAttribute("msg","您已提交 请勿重复提交...");
            return "warn";
        }
        String userId = WXUserUtil.findCookie(request);
        repaireInfoVO.setCreator(userId);
        try {
            if (!file.isEmpty()) {
                String storePath = MyPropertiesConfigurer.ctxPropertiesMap.get("file.storage.path");
                String fileName = file.getOriginalFilename();
                File filepath = new File(storePath, fileName);
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();//如果目录不存在，创建目录
                }
                file.transferTo(new File(storePath + "/" + fileName));//把文件写入目标文件地址
                repaireInfoVO.setPicAddress(storePath + "/" + fileName);//存库
            }
            repaireInfoVO.setSource("3"); // 来源为微信报修
            if (!StringUtils.isEmpty(repaireInfoVO.getCurrentId())) {
                repaireInfoVO.setSource("4");  // 扫一扫来源为扫一扫
            }
            service.insertByUserId(userId, repaireInfoVO);
            /*RepaireInfo repaireInfo = service.getRepaireInfo(orderId + "");
            String workOrderId = repaireInfo.getWorkOrderId();*/
            notifyCreator(userId);
            //  工程师微信端提醒
            /*if(repaireInfo.getStatus().equals("00")){ //只有待流转的单子 才通知坐席
                User in = new User();
                in.setRoleId(2);  //改为提箱座席
                List<User> list = userService.findUser(in);
                StringBuffer sb = new StringBuffer();
                for(User u:list){
                    sb.append(u.getUserName());
                    sb.append("|");
                }
                String toUser = sb.substring(0,sb.length()-1);
                StringBuffer socketMsg = new StringBuffer("您有工单需要处理，单号："+ workOrderId +"；");
                socketMsg.append("您有工单需要处理，单号：<a href=javascript:process_00("+orderId+",00)>"+ workOrderId +"，请点击处理；");
                infoHandler().sendMessageToUsersByName(toUser,new TextMessage(socketMsg));
            }*/
        } catch (Exception e) {
            log.error("com.weixin.web.WXRepaireController.addWorkOrder error |",e);
            model.addAttribute("msg","系统内部错误！");
            return "error";
        }
        return  "forward:/weixin/repaire/list";
    }

    private void notifyCreator(String userId) throws Exception {
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.REPAIRE_AGENT_ID);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(userId);
        Text text = new Text();
        Dict dict = null;
        if(DateUtil.isWorkDate()){
            dict = dictService.getDict(Constants.CREATE_MSG);
        }else{
            dict = dictService.getDict(Constants.NOWORKER_CREATE_MSG);
        }
        text.setContent(dict.getDictValue().replace("\n","\n"));
        wxMsg.setText(text);
        weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
    }

    @RequestMapping(value = "repaire/list")
    public String repaireHistory(HttpServletRequest request, Model model){
        String userId = WXUserUtil.findCookie(request);
        if(StringUtils.isEmpty(userId)){
            try{
                userId = request.getQueryString().split("=")[1];
            }catch (Exception e){
                log.error("get query string error | ",e);
            }
        }
        if(StringUtils.isEmpty(userId)){
            log.info("com.weixin.web.WXRepaireController.repaireHistory userid is null ");
            model.addAttribute("repaireInfos",new ArrayList<>());
            model.addAttribute("userId",userId);
            return "repair/list";
        }
        RepaireInfoVO repaireInfo = new RepaireInfoVO();
        repaireInfo.setCreator(userId);
        List<RepaireInfo> repaireInfoList = service.getRepaireInfoList(repaireInfo);
        repaireInfoList.forEach(info ->{
            info.setStatus(Constants.getStatus(info.getStatus()));
            info.setMachineType(Constants.getMachineType(info.getMachineType()));
            if(StringUtils.isEmpty(info.getFloor())){
                info.setAddress(Constants.getAddress(info.getAddress()));
            }else{
                if("04".equals(info.getAddress())){
                    info.setAddress(Constants.getAddress(info.getAddress()) +"-"+info.getFloor());
                }else{
                    info.setAddress(Constants.getAddress(info.getAddress()) +"-"+info.getFloor()+"楼");
                }
            }
            info.setAddress(Constants.getAddress(info.getAddress()));
        });
        model.addAttribute("repaireInfos",repaireInfoList);
        model.addAttribute("userId",userId);
        return "repair/list";
    }

    /**
     * 进入满意度评价页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "to_customer_satisfaction/{id}")
    public String toCustomerSatisfaction(@PathVariable("id") String id,Model model ){
        RepaireInfo repaireInfo = service.getRepaireInfo(id);
        if(!"04".equals(repaireInfo.getStatus())){
            log.error("the work order status is not to_customer_satisfaction id is {}",id);
            model.addAttribute("msg","此工单无法进行满意度评价...");
            return "warn";
        }
        String repairor = repaireInfo.getCurrentId();
        try {
            User in = new User();
            in.setUserName(repairor);
            List<User> users = userService.findUser(in);
            RepaireCustomerVO vo = new RepaireCustomerVO();
            vo.setDescription(repaireInfo.getDescription());
            if(users !=null && users.size()>0){
                User user = users.get(0);
                vo.setTelphone(user.getTelphone());
                vo.setRepaireDept(user.getDeptId());
            }
            vo.setMachineType(Constants.getMachineType(repaireInfo.getMachineType()));
            vo.setRepaireSubject(repaireInfo.getRepaireSubject());
            vo.setProcessSpecification(repaireInfo.getProcessSpecification());
            vo.setWorkOrderId(repaireInfo.getWorkOrderId());
            vo.setRepaireName(repaireInfo.getCurrentName());
            model.addAttribute("repaireCustomerVO",vo);
        } catch (Exception e) {
            log.error("com.weixin.web.WXRepaireController.toCustomerSatisfaction error |",e);
        }
        return "repair/customerSatisfaction";
    }

    @RequestMapping(value = "repaire/update")
    @ResponseBody
    public String update(RepaireInfoVO repaireInfoVO,Model model ){
        log.info("repaire is [{}]",repaireInfoVO.getDescription());
        service.update(repaireInfoVO);
        return "";
    }

}
